﻿using System.IO;
using System.Net;

namespace InDepth2Demo.Chapter10
{
    /// <summary>
    /// 10.1 未引入扩展方法之前的状态
    /// </summary>
    internal class BeforeExtension
    {
        //代码清单10-2 用StreamUtil将Web响应流复制到一个文件
        public static void Call()
        {
            WebRequest request = WebRequest.Create("http://manning.com");
            using (WebResponse response = request.GetResponse())
            using (Stream responseStream = response.GetResponseStream())
            using (FileStream output = File.Create("response.dat"))
            {
                StreamUtil1.Copy(responseStream, output);
            }
        }
    }

    //代码清单10-1 为流提供附加功能的一个简单的工具类
    internal static class StreamUtil1
    {
        const int BufferSize = 8192;

        public static void Copy(Stream input, Stream output)
        {
            byte[] buffer = new byte[BufferSize];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }

        public static byte[] ReadFully(Stream input)
        {
            using (MemoryStream tempStream = new MemoryStream())
            {
                Copy(input, tempStream);
                return tempStream.ToArray();
            }
        }
    }
}
